import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { QuestionGroup } from '../schemas/question-group/question-group.schema';
import { Question } from '../schemas/questions/question.schema';

@Injectable()
export class QuestionGroupService {
  constructor(
    @InjectModel(QuestionGroup.name) private questionGroupModel: Model<QuestionGroup>,
    @InjectModel(Question.name) private questionModel: Model<Question>
  ) {}

  async create(createQuestionGroupDto: {
    name: string;
    description?: string;
    questions: string[];
    type?: string;
  }): Promise<QuestionGroup> {
    // 验证所有问题ID是否存在
    if (createQuestionGroupDto.questions && createQuestionGroupDto.questions.length > 0) {
      const questionCount = await this.questionModel.countDocuments({
        _id: { $in: createQuestionGroupDto.questions }
      });
      
      if (questionCount !== createQuestionGroupDto.questions.length) {
        throw new BadRequestException('部分题目ID不存在');
      }
    }

    const createdQuestionGroup = new this.questionGroupModel(createQuestionGroupDto);
    return createdQuestionGroup.save();
  }

  async findAll(type?: string): Promise<QuestionGroup[]> {
    const query = type ? { type } : {};
    return this.questionGroupModel.find(query).populate('questions').exec();
  }

  async findOne(id: string): Promise<QuestionGroup> {
    const questionGroup = await this.questionGroupModel.findById(id).populate('questions').exec();
    if (!questionGroup) {
      throw new NotFoundException(`题目组 ID ${id} 不存在`);
    }
    return questionGroup;
  }

  async update(id: string, updateQuestionGroupDto: {
    name?: string;
    description?: string;
    questions?: string[];
    type?: string;
  }): Promise<QuestionGroup> {
    // 验证所有问题ID是否存在
    if (updateQuestionGroupDto.questions && updateQuestionGroupDto.questions.length > 0) {
      const questionCount = await this.questionModel.countDocuments({
        _id: { $in: updateQuestionGroupDto.questions }
      });
      
      if (questionCount !== updateQuestionGroupDto.questions.length) {
        throw new BadRequestException('部分题目ID不存在');
      }
    }

    const updatedQuestionGroup = await this.questionGroupModel
      .findByIdAndUpdate(id, updateQuestionGroupDto, { new: true })
      .populate('questions')
      .exec();
      
    if (!updatedQuestionGroup) {
      throw new NotFoundException(`题目组 ID ${id} 不存在`);
    }
    
    return updatedQuestionGroup;
  }

  async remove(id: string): Promise<void> {
    const result = await this.questionGroupModel.deleteOne({ _id: id }).exec();
    if (result.deletedCount === 0) {
      throw new NotFoundException(`题目组 ID ${id} 不存在`);
    }
  }

  async addQuestions(id: string, questionIds: string[]): Promise<QuestionGroup> {
    // 验证所有问题ID是否存在
    const questionCount = await this.questionModel.countDocuments({
      _id: { $in: questionIds }
    });
    
    if (questionCount !== questionIds.length) {
      throw new BadRequestException('部分题目ID不存在');
    }

    const questionGroup = await this.questionGroupModel.findById(id).exec();
    if (!questionGroup) {
      throw new NotFoundException(`题目组 ID ${id} 不存在`);
    }

    // 添加新题目，避免重复
    const existingQuestionIds = questionGroup.questions.map(q => q.toString());
    const newQuestionIds = questionIds.filter(qId => !existingQuestionIds.includes(qId));
    
    if (newQuestionIds.length === 0) {
      return await this.questionGroupModel.findById(id).populate('questions').exec();
    }

    const updatedQuestionGroup = await this.questionGroupModel.findByIdAndUpdate(
      id,
      { $push: { questions: { $each: newQuestionIds } } },
      { new: true }
    ).populate('questions').exec();

    return updatedQuestionGroup;
  }

  async removeQuestion(id: string, questionId: string): Promise<QuestionGroup> {
    const questionGroup = await this.questionGroupModel.findById(id).exec();
    if (!questionGroup) {
      throw new NotFoundException(`题目组 ID ${id} 不存在`);
    }

    const updatedQuestionGroup = await this.questionGroupModel.findByIdAndUpdate(
      id,
      { $pull: { questions: questionId } },
      { new: true }
    ).populate('questions').exec();

    return updatedQuestionGroup;
  }
}